package cn.itcast.controller.log;

import cn.itcast.domain.system.SysLog;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

@Component
@Aspect
public class LogAspect {

    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private HttpSession session;

    @Autowired
    private HttpServletRequest request;

//    @Around("execution(* cn.itcast.controller.*.*.*(..))")
    @Around("execution(* cn.itcast.controller.*.*.*(..)) && !execution(* cn.itcast.controller.system.SysLogController.*(..))")
    public Object saveLog(ProceedingJoinPoint pjp) throws Throwable {
        SysLog sysLog = new SysLog();

//        可以直接赋值的属性：
        sysLog.setId(UUID.randomUUID().toString());
        sysLog.setTime(new Date());
//        跟当前登录人有关系的属性：
        User user = (User) session.getAttribute("loginUser");
        if(user!=null){
            sysLog.setUserName(user.getUserName());
            sysLog.setCompanyId(user.getCompanyId());
            sysLog.setCompanyName(user.getCompanyName());
            sysLog.setIp(request.getRemoteAddr());  // ip地址
        }

//        取值比较复杂的属性:
        MethodSignature signature = (MethodSignature) pjp.getSignature();  // 方法签名中具有方法和注解的相关内容
        Method method = signature.getMethod(); // 从method方法对象中获取方法名称
        String name = method.getName();
        sysLog.setMethod(name); //方法名

//        判断方法上是否有RequestMapping注解
        if(method.isAnnotationPresent(RequestMapping.class)){
          RequestMapping annotation = method.getAnnotation(RequestMapping.class); //从方法中获取RequestMapping注解对象
          String action = annotation.name();  // 获取注解上的name属性值
          sysLog.setAction(action); //从方法注解上去name属性
        }
        sysLogService.save(sysLog);
        return pjp.proceed();//执行原方法
    }


}
